package com.example.core.network.body

import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.IOException
import okio.buffer

/**
 * Created by zhudongao
 * Desc
 * Date 2020/12/6
 */
class UploadProgressRequestBody(
    private val delegate: RequestBody,
    val progressCallback: ProgressResponseCallback?
) : RequestBody() {

    override fun contentType(): MediaType? = delegate.contentType()

    override fun contentLength(): Long {
        return try {
            delegate.contentLength()
        } catch (e: IOException) {
            -1
        }
    }

    override fun writeTo(sink: BufferedSink) {
        val bufferedSink:BufferedSink = CountingSink(sink, this).buffer()
        delegate.writeTo(bufferedSink)
        bufferedSink.flush()
    }
}